/*
 * @Author: daniel_du dll_2018@126.com
 * @Date: 2022-05-09 09:33:41
 * @LastEditors: daniel_du dll_2018@126.com
 * @LastEditTime: 2022-05-09 16:46:29
 * @FilePath: /safe_transmission_platform/src/server/mysqlop.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include "mysqlop.h"
#include "stdio.h"
#include <cstring>
#include "macro.h"
#include "util.h"
#include "log.h"

static sylar::Logger::ptr g_logger=DANIEL_LOG_NAME("system");

MysqlOp::MysqlOp(const daniel::MysqlInfo& info):m_mysqldb(info)
{

}

bool MysqlOp::connectToDB()
{
    return m_mysqldb.connectToDB();
}

bool MysqlOp::isStation(const std::string& stationNum)
{
    daniel::MysqlDB::queryResult result;
    {
        std::lock_guard<std::mutex> guard(m_mutex);
        result=m_mysqldb.excuteQuery("select id from station");
    }

    for(const auto& item:result){
        for(const auto& item2:item){
            if (item2==stationNum){
                return true;
            }
        }
    }
    return false;
}

//
void MysqlOp::updateKey(const std::string& stationID, const std::string& publicKey, const std::string& aesKey)
{
    const uint32_t bufSize=4096;
    char* sqlBuf=(char*)malloc(bufSize);
    memset(sqlBuf,0,bufSize);
    //需要获取当前系统时间？？
    //mysql中datetime格式     1000-01-01 00:00:00
    std::string timeNow=daniel::GetDatetime();
    sprintf(sqlBuf,"update secretKey set publicKey='%s',aesKey='%s',last_time='%s' where stationID=%s;",publicKey.c_str(),aesKey.c_str(),timeNow.c_str(),stationID.c_str());
    DANIEL_LOG_DEBUG(g_logger)<<std::string(sqlBuf)<<std::endl;
    {
        std::lock_guard<std::mutex> guard(m_mutex);
        bool ret=m_mysqldb.excuteDML(sqlBuf);
        DANIEL_ASSERT2(ret,"update secretKey failed!");
    }
}
